import strings from "../assets/strings";
import Storage from './../mod/storage';
import StringUtils from './mod.string';
import ToastUtils from './../mod/utils.toast';
import HttpData from './mod.http.deal';
// import Utils from './mod.utils';
// import ConstantUtils from './vue.constant';
import AlertUtils from '../mod/utils.alert';
import Dialog from './vue.dialog';

export default {
  // debug: true,
  debug: false,
  getDomain: function () {
    let locDomain = "http://localhost:9090";
    let serveDomain = "http://kcgl.jnaw.top/kcgl";
    return this.debug ? locDomain : serveDomain;
  },
  getUrlDomain: function () {
    let locDomain = "";
    let serveDomain = "";
    return this.debug ? locDomain : serveDomain;
  },
  getDebug: function () {
    return this.debug;
  },
  // 获取pc端地址
  getPCUrl: function () {
    return 'http://kcgl.jnaw.top';
  },
  // 获取logo地址
  getImageUrl: function () {
    return 'http://kcgl.jnaw.top/wechat/static/images/logo.png';
  },
  // 获取页面地址
  getPageUrl: function () {
    return 'http://kcgl.jnaw.top/wechat/index.html';
  },

  // TODO 所有的接口地址，test模块；module接口模块对应Name；get获取详情的接口Name；
  kInterfacePath: {
    version: '/version',
    file: {
      list: '/file/list',
      upload: '/file/addImage',
      uploadFile: '/file/addFile',
    },
    user: {
      captcha: '/user/captcha',
      query: '/user/query',
    },
    wechat: {
      is_bind: '/wechat/is_bind',
      bind: '/wechat/bind',
      login: '/wechat/login',
    },
    edu: {
      add: '/edu/add',
      list: '/edu/list',
      query: '/edu/query',
      status: '/edu/status',
      check: '/edu/check',
      update: '/edu/update',
      xzList: '/edu/xzList',
    },
    story: {
      add: '/story/add',
      list: '/story/list',
      query: '/story/query',
      update: '/story/update',
      del: '/story/del',
    },
    badge: {
      listAll: "/badge/listAll"
    }

  },
  httpType: {
    get: 'GET',
    post: 'POST',
    put: 'PUT',
    delete: 'DELETE'
  },
  httpErrorDeal: function (context, xhr) {
    let _this = this;
    let status = xhr.result;
    let statusText = xhr.data;
    console.log(
      'HTTP 错误：' + (xhr.requestUrl ? xhr.requestUrl : '') + ' ' + statusText
      + '; code =' + status);
    setTimeout(function () {

      AlertUtils.alert.dismiss();
      context.$f7.preloader.hide();
      context.$$('.infinite-scroll-preloader').hide();

      switch (status) {
        case 1:
          Dialog.toast(context, { text: '进行下一步操作失败' });
          break;
        case 2:
          if (xhr.interfaceUrl && xhr.interfaceUrl
            == _this.kInterfacePath.user.login) {
            ToastUtils.toast.show(ToastUtils.param.toast(
              { text: strings.toast.login["password-error"] }));
          } else {
            ToastUtils.toast.show(ToastUtils.param.toast(
              { text: strings.toast.login.error }));
          }
          break;
        case 3:
          if (xhr.interfaceUrl && xhr.interfaceUrl
            == _this.kInterfacePath.user.authc) {
            ToastUtils.toast.show(ToastUtils.param.toast(
              { text: strings.toast["without-permission"] }));
          } else {
          }
          break;
        case 4:
          Dialog.toast(context, { text: '验证码错误！' });
          break;
        case 5:
          Dialog.toast(context, { text: '提交数据有误，请核实后重新提交！' });
          break;
        case 7:
          Dialog.toast(context, { text: '当前信息不存在，请重新确认！' });
          break;
        case 8:
          ToastUtils.toast.show(ToastUtils.param.toast(
            { text: '部分人员未开通权限！' }));
          break;
        case 9:
          Dialog.toast(context, { text: '密码修改失败！' });
          break;
        case 10:
          Dialog.toast(context, { text: '数据异常，请稍后重试！' });
          break;
        case 11:
          Dialog.toast(context, { text: '保存数据异常，请稍后重试！' });
          break;
        case 12:
          Dialog.toast(context, { text: '修改数据异常，请稍后重试！' });
          break;
        case 13:
          Dialog.toast(context, { text: '删除数据异常，请稍后重试！' });
          break;
        case 15:
          Dialog.toast(context, { text: '文件复制错误，请稍后重试！' });
          break;
        case 16:
          Dialog.toast(context, { text: '图片压缩错误，请稍后重试！' });
          break;
        case 17:
        case 18:
        case 19:
        case 20:
        case 22:
        case 23:
        case 24:
          Dialog.toast(context, { text: '身份证号码格式错误，请核实！' });
          break;
        case 21:
          ToastUtils.toast.show(ToastUtils.param.toast(
            { text: '验证码错误！' }));
          break;
        case 25:
          Dialog.toast(context, { text: '该账户已存在！' });
          break;
        case 26:
          Dialog.toast(context, { text: '查询记录不存在！' });
          break;
        case 27:
          Dialog.toast(context, { text: '用户已离职，请联系人事部门!' });
          break;
        case 29:
          Dialog.toast(context, { text: '多级审批，请等待当前阶段审批人' });
          break;
        case 30:
          ToastUtils.toast.show(ToastUtils.param.toast(
            { text: '绑定的账号不存在!' }));
          break;
        case 400:
          Dialog.toast(context, { text: '请求错误！' });
          break;
        case 401:
          Dialog.toast(context, { text: '未授权，请登录！' });
          break;
        case 403:
          Dialog.toast(context, { text: '拒绝访问！' });
          break;
        case 404:
          Dialog.toast(context, { text: xhr.interfaceUrl + '，请求地址出错！' });
          break;
        case 408:
          Dialog.toast(context, { text: '请求超时！' });
          break;
        case 500:
          Dialog.toast(context, { text: '服务器内部错误！' });
          break;
        case 501:
          Dialog.toast(context, { text: '服务未实现！' });
          break;
        case 502:
          Dialog.toast(context, { text: '后台服务正在更新，稍后再试' });
          break;
        case 503:
          Dialog.toast(context, { text: '服务不可用！' });
          break;
        case 504:
          Dialog.toast(context, { text: '网关超时！' });
          break;
        case 505:
          Dialog.toast(context, { text: 'HTTP版本不受支持！' });
          break;
        default:
          if (statusText.search('timeout') != -1) {
            // 请求超时
            Dialog.toast(context, { text: '请求超时，请稍后尝试！' });
          } else if (statusText.search('Network Error') != -1) {
            // 网络断开
            // Dialog.toast(context, { text: '网络断开，请检查网络！' });
          } else {
            Dialog.toast(context, { text: statusText + '，code=' + status });
          }
          break;
      }
    }, 600);
  },
  ajax: function (context, params) {
    let _this = this;
    try {
      if (context) {
        if (params) {
          if (params != null && params != '' && params != {}) {
            if (typeof params != 'object') {
              params = JSON.parse(params);
            }
            let domain = params.domain ? params.domain : _this.getDomain();
            let url = params.url ? params.url : '';
            if (url == '') {
              console.log('Interface url is null');
              return;
            }

            let interfaceUrl = url;
            url = domain + url;
            let data = params.data ? params.data : {};
            let errorWarnInfo = params.warn_error ? params.warn_error : '失败！';
            let type = params.type ? params.type.toUpperCase()
              : _this.httpType.post;
            let async = (params.async != undefined) ? params.async : true;
            let cache = (params.cache != undefined) ? params.cache : true;
            let processData = (params.processData != undefined)
              ? params.processData : true;
            let contentType = (params.contentType != undefined)
              ? params.contentType : 'application/x-www-form-urlencoded';
            let successFuc = (params.success && typeof params.success
              == "function") ? params.success : null;
            let errorFuc = (params.error && typeof params.error == "function")
              ? params.error : null;
            let dataType = params.dataType ? params.dataType : 'jsonp';

            let isAuthc = params.isAuthc ? params.isAuthc : false;
            let responseData = params.responseData ? params.responseData : false;

            if (data.page != undefined || data.page != null) {
              context.$$('.infinite-scroll-preloader').show();
            }
            context.$f7.data.axios({
              method: type,
              url: url,
              params: (type == _this.httpType.post) ? '' : data,
              data: data,
              responseType: 'json',
              withCredentials: true,
              //timeout: 10000, // 设置请求超时时间10s
            }).then(function (response) {
              let res = response.data;
              if (typeof res != 'object') {
                res = StringUtils.toJson(res);
              }
              if (responseData == true) { // 不进行判断，直接返回数据
                if (successFuc != null && typeof successFuc == "function") {
                  successFuc(res);
                }
                return false;
              }
              // context.$f7.preloader.hide();
              let isAvail = HttpData.isAvailable(context, res);
              if (isAvail) {
                if (res.result == 0) {
                  if (successFuc != null && typeof successFuc == "function") {
                    successFuc(res);
                  } else {
                    console.log('成功请求返回：', res);
                  }
                } else {
                  res.requestUrl = url;
                  res.interfaceUrl = interfaceUrl;
                  if (errorFuc != null && typeof errorFuc == "function") {
                    errorFuc(res);
                  } else {
                    _this.httpErrorDeal(context, res);
                  }
                }
              } else {
                if (errorFuc != null && typeof errorFuc == "function") {
                  errorFuc(res);
                } else {
                  ToastUtils.toast.show(ToastUtils.param.toast(
                    { text: '返回数据格式不正确！' }));
                }
              }

            }).catch(function (error) {
              // if (!error.messages&&error.)
              let statusStr = '';
              if (error.response != undefined) {
                statusStr = error.response.status;
              } else {
                statusStr = -1;
              }
              let resData = {
                result: statusStr,
                data: error.message
              };
              resData.requestUrl = url;
              resData.interfaceUrl = interfaceUrl;
              _this.httpErrorDeal(context, resData);
              if (errorFuc != null && typeof errorFuc == "function") {
                errorFuc(resData);
              }
            });
          } else {
            throw Error('Params is null!');
          }
        } else {
          throw Error('Params is undefined!');
        }
      } else {
        throw Error('VueComponent object is undefined!');
      }
    } catch (exception) {
      ToastUtils.toast.show(ToastUtils.param.toast(
        { text: '出现未知错误，请联系管理员！' }));
      console.log(exception);
    }
  },
  otherAjax: function (context, params) {
    let _this = this;
    try {
      if (context) {
        if (params) {
          if (params != null && params != '' && params != {}) {
            if (typeof params != 'object') {
              params = JSON.parse(params);
            }
            let url = params.url ? params.url : '';
            if (url == '') {
              console.log('Interface url is null');
              return;
            }

            let interfaceUrl = url;
            let data = params.data ? params.data : {};
            let type = params.type ? params.type.toUpperCase()
              : _this.httpType.post;
            let successFuc = (params.success && typeof params.success
              == "function") ? params.success : null;
            let errorFuc = (params.error && typeof params.error == "function")
              ? params.error : null;

            if (data.page != undefined || data.page != null) {
              context.$$('.infinite-scroll-preloader').show();
            }
            context.$f7.data.axios({
              method: type,
              url: url,
              params: (type == _this.httpType.post) ? '' : data,
              data: data,
              responseType: 'json',
              withCredentials: true,
            }).then(function (response) {
              let res = response.data;
              if (typeof res != 'object') {
                res = StringUtils.toJson(res);
              }
              successFuc(res);

            }).catch(function (error) {
              let statusStr = '';
              if (error.response != undefined) {
                statusStr = error.response.status;
              } else {
                statusStr = -1;
              }
              let resData = {
                result: statusStr,
                data: error.message
              };
              resData.requestUrl = url;
              resData.interfaceUrl = interfaceUrl;
              if (errorFuc != null && typeof errorFuc == "function") {
                errorFuc(resData);
              }
            });
          } else {
            throw Error('Params is null!');
          }
        } else {
          throw Error('Params is undefined!');
        }
      } else {
        throw Error('VueComponent object is undefined!');
      }
    } catch (exception) {
      ToastUtils.toast.show(ToastUtils.param.toast(
        { text: '出现未知错误，请联系管理员！' }));
      console.log(exception);
    }
  },
  // 心跳
  runAuthc: function (context, warnInfo) {
    let _this = this;
    // console.log('我进来了心跳事件当中了');
    console.log('before =======' + context.$f7.data.authc.count);
    let resCount = parseInt(parseInt(context.$f7.data.authc.count) + 1);
    // context.$f7.data.authc.count = parseInt(parseInt(context.$f7.data.authc.count) + 1);
    console.log('klsjkfd---=====' + context.$f7.data.authc.count);
    console.log('klsjkfd---=====' + context.$f7.data.authc.period);
    console.log('klsjkfd---=====' + resCount);
    context.$f7.data.authc.count = resCount;
    // 传参的初始值
    let isBackMode = false;
    let longitude = '', latitude = '', address = '';
    let manufacturer = '', model = '', version = '';
    if (context.$f7.data.local_version != '') {
      version = context.$f7.data.local_version;
    }
    if (context.$f7.data.longitude != '') {
      longitude = context.$f7.data.longitude;
    }
    if (context.$f7.data.latitude != '') {
      latitude = context.$f7.data.latitude;
    }
    if (context.$f7.data.address != '') {
      address = context.$f7.data.address;
    }
    try {
      manufacturer = device.manufacturer ? device.manufacturer : '';
      model = device.model ? device.model : '';
      isBackMode = cordova.plugins.backgroundMode.isActive() || false;
    } catch (e) {
      console.log(e);
    }
    let ajaxData = {
      type: 'app',
      version: version,
      longitude: longitude,
      latitude: latitude,
      address: address,
      manufacturer: manufacturer,
      model: model,
      back_mode: isBackMode,
    };
    let _successAuthc = function (res) {
      context.$f7.data.authc.count = 0;
      let nowTimestamp = new Date().getTime();
      context.$f7.data.authc.startTime = nowTimestamp;
      if (warnInfo) {
        ToastUtils.toast.show(ToastUtils.param.toast({ text: warnInfo }));
      }
    };
    let ajaxParams = {
      isAuthc: true,
      url: _this.kInterfacePath.user.authc,
      data: ajaxData,
      warn_error: '心跳失败！',
      success: _successAuthc,
    };
    _this.ajax(context, ajaxParams);
  },
  logOutToReLogin: function (context) {
    let _this = this;
    context.$f7.dialog.preloader();
    Storage.remove('userInfo');
    Storage.remove('sd_curUserInfo');
    Storage.remove('userid');
    Storage.remove('username');
    // Storage.remove('telephone');
    // Storage.remove('password');
    context.$root._data.tab_id = 'message';
  },
}